package com.jungle.bfi.generator;

import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.MapModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateModelException;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TemplateBuilder {
    private Configuration configuration;

    public TemplateBuilder(String author) throws TemplateModelException {
        configuration = new Configuration(Configuration.VERSION_2_3_32);
        // 设置编码
        configuration.setDefaultEncoding("UTF-8");
        // 设置全局变量
        Map<String, Object> map = new HashMap<>();
        map.put("author", author);
        map.put("since", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        MapModel mapModel = new MapModel(map, new BeansWrapper(Configuration.VERSION_2_3_32));
        configuration.setAllSharedVariables(mapModel);
    }

    public Template build(File templateDir, String templateName) throws Exception {
        configuration.setDirectoryForTemplateLoading(templateDir);
        return configuration.getTemplate(templateName);
    }
}
